<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>数据采集系统</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta
            name="viewport"
            content="width=device-width, initial-scale=1, maximum-scale=1"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <link
            rel="stylesheet"
            title="default"
            href="amis-sdk/antd.css"
    />
    <link rel="stylesheet" href="amis-sdk/helper.css"/>
    <link
            rel="stylesheet"
            href="amis-sdk/iconfont.css"
    />
    <script src="amis-sdk/sdk.js"></script>
    <script src="history.js"></script>
    <style>
        html,
        body,
        .app-wrapper {
            position: relative;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
<div id="root" class="app-wrapper"></div>
<script>
    // 定义为全局函数
    function logout() {
        // console.log('退出登录');
        // 调用退出接口
        fetch('/admin/logout', { // 替换为实际的退出接口地址
            method: 'POST', // 根据接口要求选择合适的请求方法
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                // 如果需要携带额外参数，可以在这里添加
            })
        })
            .then(response => {
                if (response.ok) {
                    // console.log('退出成功');
                    // 跳转到登录页面
                    window.location.href = '/login.html';
                } else {
                    console.error('退出失败', response.status);
                    alert('退出失败，请稍后再试');
                }
            })
            .catch(error => {
                console.error('退出时发生错误', error);
                alert('退出时发生错误，请检查网络或联系管理员');
            });
        // 在这里添加退出登录的逻辑，例如清除本地存储、跳转到登录页面等
        // window.location.href = '/login.html'; // 示例：跳转到登录页面
    }

    // 定义获取系统配置的函数
    function fetchSystemConfig() {
        return fetch('/sys/config') // 假设这是获取系统配置的接口
            .then(response => {
                if (!response.ok) throw new Error('获取配置失败');
                return response.json();
            })
            .then(res => ({
                systemName: res.data.systemName || '插件管理系统' // 默认值
            }))
            .catch(error => {
                console.error('获取系统配置失败:', error);
                return { systemName: '插件管理系统' }; // 降级处理
            });
    }

    (async function () {
        // 先获取系统配置
        const config = await fetchSystemConfig();

        let amis = amisRequire('amis/embed');
        const match = amisRequire('path-to-regexp').match;

        // 如果想用 browserHistory 请切换下这处代码, 其他不用变
        // const history = History.createBrowserHistory();
        const history = History.createHashHistory();

        const app = {
            type: 'app',
            brandName: config.systemName,
            logo: '/favicon.ico',
            header: {
                type: 'tpl',
                inline: false,
                className: 'w-full',
                tpl: '<div class="flex justify-between"><div>v1.0.0<!--顶部区域左侧--></div><div><a href="javascript:void(0);" onclick="logout()">退出登录</a></div></div>'
            },
            // footer: '<div class="p-2 text-center bg-light"><a href="http://www.ahbcht.com" target="_blank"> 安徽百诚慧通科技股份有限公司 </a></div>',
            // asideBefore: '<div class="p-2 text-center">菜单前面区域</div>',
            // asideAfter: '<div class="p-2 text-center">菜单后面区域</div>',
            api: '/sys/site'
        };

        function normalizeLink(to, location = history.location) {
            to = to || '';

            if (to && to[0] === '#') {
                to = location.pathname + location.search + to;
            } else if (to && to[0] === '?') {
                to = location.pathname + to;
            }

            const idx = to.indexOf('?');
            const idx2 = to.indexOf('#');
            let pathname = ~idx
                ? to.substring(0, idx)
                : ~idx2
                    ? to.substring(0, idx2)
                    : to;
            let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : '';
            let hash = ~idx2 ? to.substring(idx2) : location.hash;

            if (!pathname) {
                pathname = location.pathname;
            } else if (pathname[0] != '/' && !/^https?\:\/\//.test(pathname)) {
                let relativeBase = location.pathname;
                const paths = relativeBase.split('/');
                paths.pop();
                let m;
                while ((m = /^\.\.?\//.exec(pathname))) {
                    if (m[0] === '../') {
                        paths.pop();
                    }
                    pathname = pathname.substring(m[0].length);
                }
                pathname = paths.concat(pathname).join('/');
            }

            return pathname + search + hash;
        }

        function isCurrentUrl(to, ctx) {
            if (!to) {
                return false;
            }
            const pathname = history.location.pathname;
            const link = normalizeLink(to, {
                ...location,
                pathname,
                hash: ''
            });

            if (!~link.indexOf('http') && ~link.indexOf(':')) {
                let strict = ctx && ctx.strict;
                return match(link, {
                    decode: decodeURIComponent,
                    strict: typeof strict !== 'undefined' ? strict : true
                })(pathname);
            }

            return decodeURI(pathname) === link;
        }

        let amisInstance = amis.embed(
            '#root',
            app,
            {
                location: history.location,
                data: {
                    // 全局数据，是受控的数据
                },
                context: {
                    // 全局上下文数据, 非受控的数据，无论哪一层都能获取到，包括弹窗自定义数据映射后都能获取到。
                    // 可以用来放一下全局配置等。比如 API_HOST, 这样页面配置里面可以通过 ${API_HOST} 来获取到。
                    API_HOST: 'https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com'
                }
            },
            {
                // watchRouteChange: fn => {
                //   return history.listen(fn);
                // },
                requestAdaptor: (api) => {
                    // console.log('全局请求适配器', api)
                    return api;
                },
                responseAdaptor: (payload, response) => {
                    //console.log('全局响应适配器payload', payload)
                    //console.log('全局响应适配器response', response)
                    // 检查后端返回的状态码
                    if (response.status === 401) {
                        // 重定向到登录页面
                        window.location.href = '/login.html'; // 替换为你的登录页面路径
                    }
                    return response
                },
                updateLocation: (location, replace) => {
                    location = normalizeLink(location);
                    if (location === 'goBack') {
                        return history.goBack();
                    } else if (
                        (!/^https?\:\/\//.test(location) &&
                            location ===
                            history.location.pathname + history.location.search) ||
                        location === history.location.href
                    ) {
                        // 目标地址和当前地址一样，不处理，免得重复刷新
                        return;
                    } else if (/^https?\:\/\//.test(location) || !history) {
                        return (window.location.href = location);
                    }

                    history[replace ? 'replace' : 'push'](location);
                },
                jumpTo: (to, action) => {
                    if (to === 'goBack') {
                        return history.goBack();
                    }

                    to = normalizeLink(to);

                    if (isCurrentUrl(to)) {
                        return;
                    }

                    if (action && action.actionType === 'url') {
                        action.blank === false
                            ? (window.location.href = to)
                            : window.open(to, '_blank');
                        return;
                    } else if (action && action.blank) {
                        window.open(to, '_blank');
                        return;
                    }

                    if (/^https?:\/\//.test(to)) {
                        window.location.href = to;
                    } else if (
                        (!/^https?\:\/\//.test(to) &&
                            to === history.pathname + history.location.search) ||
                        to === history.location.href
                    ) {
                        // do nothing
                    } else {
                        history.push(to);
                    }
                },
                isCurrentUrl: isCurrentUrl,
                theme: 'antd'
            }
        );

        history.listen(state => {
            amisInstance.updateProps({
                location: state.location || state
            });
        });
    })();
</script>
</body>
</html>
